package com.zoe.onelink.core.web.filter;

import cn.hutool.http.ContentType;
import com.zoe.onelink.util.SpringUtil;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>标题: RequestBody缓存器</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-08-05
 */
public class RequestBodyWrapperFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 如果是application/json类型的请求,进行缓存包装,用于日志记录
        if (SpringUtil.isApplicationJson(request.getContentType()) && request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            ContentCachingRequestWrapper requestParamWrapper = new ContentCachingRequestWrapper(httpServletRequest);
            chain.doFilter(requestParamWrapper, response);
        } else {
            chain.doFilter(request, response);
        }

    }
}
